<template>
    <div class="container">
        <h2>OCR文字识别</h2>

        <el-card class="ocr-card">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="上传图片识别" name="upload">
                    <el-upload class="upload-area" drag action="#" :auto-upload="false" :on-change="handleFileChange"
                        :limit="1" :file-list="fileList" :before-upload="beforeUpload">
                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">
                            拖拽图片到此处，或 <em>点击上传</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                支持jpg、jpeg、png格式图片，文件大小不超过10MB
                            </div>
                        </template>
                    </el-upload>

                    <div class="button-container">
                        <el-button type="primary" @click="handleUpload" :loading="uploading" :disabled="!selectedFile">
                            开始识别
                        </el-button>
                        <el-button @click="resetUpload">重置</el-button>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="网络图片识别" name="url">
                    <el-form :model="urlForm" :rules="urlRules" ref="urlFormRef">
                        <el-form-item prop="imageUrl">
                            <el-input v-model="urlForm.imageUrl" placeholder="请输入图片URL" clearable>
                                <template #append>
                                    <el-button @click="handleRecognizeUrl" :loading="recognizing">
                                        识别
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 识别结果 -->
        <el-card v-if="recognitionResult" class="result-card">
            <template #header>
                <div class="result-header">
                    <span>识别结果</span>
                    <el-button type="primary" size="small" @click="copyResult">
                        复制结果
                    </el-button>
                </div>
            </template>
            <div class="result-content">
                <pre>{{ recognitionResult }}</pre>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'

const activeTab = ref('upload')
const fileList = ref([])
const selectedFile = ref(null)
const uploading = ref(false)
const recognizing = ref(false)
const recognitionResult = ref('')

const urlForm = reactive({
    imageUrl: ''
})

const urlRules = {
    imageUrl: [
        { required: true, message: '请输入图片URL', trigger: 'blur' },
        { type: 'url', message: '请输入有效的URL', trigger: 'blur' }
    ]
}

const urlFormRef = ref(null)

// 处理文件选择
const handleFileChange = (file) => {
    fileList.value = [file]
    selectedFile.value = file.raw
}

// 重置上传
const resetUpload = () => {
    fileList.value = []
    selectedFile.value = null
    recognitionResult.value = ''
}

// 文件上传前的校验
const beforeUpload = (file) => {
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过10MB')
    }
    return isLt10M
}

// 上传并识别图片
const handleUpload = async () => {
    if (!selectedFile.value) {
        ElMessage.warning('请先选择图片')
        return
    }

    uploading.value = true
    recognitionResult.value = ''

    try {
        const formData = new FormData()
        formData.append('file', selectedFile.value)
        formData.append('language', 'chi_sim') // 传递语言参数
        const res = await axios.post('/api/ocr/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        recognitionResult.value = res.data
        ElMessage.success('识别成功')
    } catch (error) {
        console.error('OCR识别出错:', error)
        if (error.response) {
            console.error('响应数据:', error.response.data)
            console.error('状态码:', error.response.status)
            console.error('响应头:', error.response.headers)
        } else if (error.request) {
            console.error('请求未收到响应:', error.request)
        } else {
            console.error('请求配置错误:', error.config)
        }
        ElMessage.error('识别失败')
    } finally {
        uploading.value = false
    }
}

// 识别网络图片
const handleRecognizeUrl = async () => {
    if (!urlFormRef.value) return

    urlFormRef.value.validate(async (valid) => {
        if (valid) {
            recognizing.value = true
            recognitionResult.value = ''

            try {
                const res = await axios.get('/api/ocr/recognize-url', {
                    params: {
                        imageUrl: urlForm.imageUrl,
                        language: 'chi_sim' // 传递语言参数
                    }
                })
                recognitionResult.value = res.data
                ElMessage.success('识别成功')
            } catch (error) {
                console.error('OCR识别出错:', error)
                if (error.response) {
                    console.error('响应数据:', error.response.data)
                    console.error('状态码:', error.response.status)
                    console.error('响应头:', error.response.headers)
                } else if (error.request) {
                    console.error('请求未收到响应:', error.request)
                } else {
                    console.error('请求配置错误:', error.config)
                }
                ElMessage.error('识别失败')
            } finally {
                recognizing.value = false
            }
        }
    })
}

// 复制识别结果
const copyResult = () => {
    if (!recognitionResult.value) return

    navigator.clipboard.writeText(recognitionResult.value)
        .then(() => {
            ElMessage.success('复制成功')
        })
        .catch(() => {
            ElMessage.error('复制失败')
        })
}
</script>

<style scoped>
.container {
    padding: 20px;
}

.ocr-card {
    margin-bottom: 20px;
}

.upload-area {
    width: 100%;
    margin-bottom: 20px;
}

.button-container {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
}

.result-card {
    margin-top: 30px;
}

.result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.result-content {
    max-height: 400px;
    overflow-y: auto;
}

.result-content pre {
    white-space: pre-wrap;
    word-break: break-word;
    margin: 0;
    font-family: Consolas, Monaco, monospace;
}
</style>